package fi.pyppe.android.gps.listen;

import java.util.Iterator;

import fi.pyppe.android.gps.PyppeGPSActivity;

import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.GpsStatus.Listener;
import android.os.Bundle;

/**
 * PyppeGPSLocationListener
 * 
 * @author Pyppe
 */
public class PyppeGPSLocationListener implements LocationListener, Listener {

  private PyppeGPSActivity pyppeGPSActivity;

  public PyppeGPSLocationListener(PyppeGPSActivity activity) {
    pyppeGPSActivity = activity;
  }

  public void onLocationChanged(Location location) {
    try {
      if (location != null) {
        pyppeGPSActivity.updateLocation(location);
      }
    } catch (Exception ex) {
      pyppeGPSActivity.setStatusText(ex.getMessage());
    }
  }

  public void onProviderDisabled(String provider) {
    pyppeGPSActivity.restartLocationManagers();
  }

  public void onProviderEnabled(String provider) {
    pyppeGPSActivity.restartLocationManagers();
  }

  public void onStatusChanged(String provider, int status, Bundle extras) {

  }
  
  public void onGpsStatusChanged(int event) {

    switch (event) {
    
    case GpsStatus.GPS_EVENT_STARTED:
      pyppeGPSActivity.setStatusText("GPS started, waiting for fix");
      break;
    
    case GpsStatus.GPS_EVENT_FIRST_FIX:
      pyppeGPSActivity.setStatusText("GPS-fix obtained");
      break;

    case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
      GpsStatus status = pyppeGPSActivity.gpsLocationManager.getGpsStatus(null);
      Iterator<GpsSatellite> it = status.getSatellites().iterator();
      int count = 0;
      while (it.hasNext()) {
        count++;
        it.next();
      }
      pyppeGPSActivity.setNumberOfSatellites(count);
      break;

    case GpsStatus.GPS_EVENT_STOPPED:
      pyppeGPSActivity.setStatusText("GPS stopped");
      break;

    }

  }

}
